package fregat.connector.channel;

import fregat.base.util.ConfigurationBundle;
import fregat.connector.ConnectorService;

/**
 * Simple channel that directly connects two worker instances.
 * Can be used to connect two databases without a database link.
 *
 * @author Alexander Mann <br><b><i>ECO_L O G</i> &nbsp Logistiksysteme GmbH</b>
 * @version 1.0
 */
public class TransferChannel extends AbstractChannel {
  private long timeout;

  public TransferChannel(String name) {
    super(name);
    ConfigurationBundle configuration = ConnectorService.getConfiguration();

    String configPath = "channel.config." + getName();

    timeout = configuration.getConfigurationInteger(configPath + ".timeout");

    if (timeout < 0) {
      timeout = 5000;
    }
  }

  /**
   * Sends data to the connected workers.
   *
   * @param data Data received from a worker
   * @return True, if send was successful
   */
  public boolean send(byte[] data) {
    boolean success = received(data);

    if (!success) {
      synchronized (this) {
        try {
          wait(timeout);
        } catch (InterruptedException ex) {
        }
      }
    }

    return success;
  }

  public void start() {
    super.start();
    connected(true);
  }

  public void shutdown() {
    synchronized (this) {
      notify();
    }
    connected(false);
    super.shutdown();
  }
}
